import React, {createRef, useEffect, useState} from 'react';
import {
  View,
  Dimensions,
  ActivityIndicator,
  StyleSheet,
  TouchableWithoutFeedback,
  ToastAndroid,
} from 'react-native';
import {getLogger} from '@siteed/react-native-logger';
import {loginInnerTeacher} from '../store/rootSlice.ts';
import {useDispatch} from 'react-redux';
import {useStyles} from '../resources/StyleConstants.js';
import WebView from 'react-native-webview';
const logger = getLogger('App');
import qs from 'qs';
import Ionicons from 'react-native-vector-icons/Ionicons';
import ModalViewUtil from '../components/ModalViewUtil.tsx';

export default function InnerLoginView(props) {
  const dispatch = useDispatch();
  const url = 'http://172.22.181.69/h5/#/pages/authorizeLogin';
  const [loading, setLoading] = useState(true);
  const handleNavigationStateChange = navState => {
    console.log(navState);
    try {
      if (navState.url) {
        // 从navState的url中取query参数
        const params = qs.parse(navState.url.split('?')[1]);

        console.log('params:', params);
        console.log('url--->', navState.url);
        logger.info('url:', JSON.stringify(navState));
        logger.info('params:', JSON.stringify(params));
        if (navState.url.indexOf('logoutCustom') >= 0 && !navState.loading) {
          setLoading(false);
          return;
        }
        if (
          navState.url.indexOf('http://172.22.181.69/h5/') >= 0 &&
          navState.url.indexOf('uid=') >= 0
        ) {
          const uid = params.uid.split('#')[0];
          dispatch(
            loginInnerTeacher(uid, () => {
              props.loginComplete && props.loginComplete();
            }),
          );
        }
      }
    } catch (error) {
      ToastAndroid.show(error.message, ToastAndroid.SHORT);
    }
  };
  const {styles} = useStyles();

  useEffect(() => {
    const handler = setTimeout(() => {
      ModalViewUtil.dismissBottomView();
    }, 60 * 1000);
    return () => {
      clearTimeout(handler);
    };
  }, []);

  return (
    <View
      style={{
        width: Dimensions.get('window').width * 0.8,
        height: Dimensions.get('window').height * 0.4,
        ...styles.popUpContainer,
      }}>
      {loading ? (
        <WebView
          source={{uri: 'http://172.22.181.69:8080/cas/casClient/logoutCustom'}}
          style={styless.webview}
          onNavigationStateChange={handleNavigationStateChange}
        />
      ) : (
        <WebView
          source={{uri: url}}
          onLoadEnd={() => setLoading(false)}
          style={styless.webview}
          onNavigationStateChange={handleNavigationStateChange}
        />
      )}
      <TouchableWithoutFeedback onPress={() => ModalViewUtil.dismissView()}>
        <Ionicons
          name={'close-circle-outline'}
          size={50}
          color={'black'}
          style={{position: 'absolute', top: 20, right: 20, zIndex: 1000}}
        />
      </TouchableWithoutFeedback>
    </View>
  );
}
const styless = StyleSheet.create({
  container: {
    flex: 1,
  },
  loadingIndicator: {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: [{translateX: -25}, {translateY: -25}],
  },
  webview: {
    flex: 1,
    height: Dimensions.get('window').height * 0.6,
  },
});
